<template>
  <u-popup ref="filterPop" :safeArea="false" @change="popChange" :show="show" class="search-pop-box">
    <view class="input-pop">
      <view class="header">
        <text>更多查询</text>
        <u-icon name="close" class="close-icon" @click="closePop" type="closeempty" size="20px" color="#CCCCCC" />
      </view>
      <view class="conent-wrap">
        <view class="main nyj-form-pop" style="min-height: 300rpx">
          <!-- <view class="items">
            <view class="label">企业类别</view>
            <uni-data-select v-model="filterInput.customerType" :localdata="customerDatas"
              @change="changeCustomer"></uni-data-select>
          </view> -->
          <view class="items">
            <view class="label">企业名称</view>
            <view class="items-input clear-space-item">
              <uni-easyinput v-model="selectedText" placeholder="请选择企业名称" :disabled="true" :clearable="false"
                @click.native="chooseStatus">
              </uni-easyinput>
              <u-icon name="" class="name-close-icon uni-icons uniui-clear" type="closeempty" size="20px"
                color="#CCCCCC" v-if="!!selectedText" @click="clearInput" />
            </view>
          </view>

          <view class="items" v-if="dateType == 0">
            <view class="label">时间</view>
            <view class="items-input">
              <uni-datetime-picker type="daterange" ref="datePickerRefs" v-model="timeRange" @change="confirmSdate"
                hide-clear-button />
            </view>
          </view>
          <view class="items" v-else>
            <view class="label">时间</view>
            <view class="items-input">
              <view @click="showDate" class="nyj-input-box">{{
                timeRangeMonth
                }}</view>
            </view>
          </view>
        </view>

        <u-datetime-picker :show="showPicker" :mode="dateType == 0 ? 'date' : 'year-month'" v-model="endTime"
          :start-date="minDate" :end-date="maxDate" @confirm="confirmEdate"
          @cancel="showPicker = false"></u-datetime-picker>
      </view>
      <view v-if="showPopup" class="nyj-scroll-pop">
        <scroll-view class="scroll-view" scroll-y="true">
          <uni-easyinput prefixIcon="search" :maxlength="50" v-model="keyword" placeholder="请输入关键字"
            :adjust-position="false">
          </uni-easyinput>
          <view class="scroll-main" style="margin-top: 20rpx">
            <view :key="index" class="scroll-view-item" @click="statusClickItem(item)"
              :class="{ 'active-item': item.checked }" v-for="(item, index) in dataLists">
              <view>{{ item.text }}</view>
              <view class="checked-icon" v-if="item.checked">√</view>
            </view>
          </view>
        </scroll-view>
        <view class="scroll-footer nyj-btns">
          <u-button class="cancel two" plain @click="cancleStatus">
            取消
          </u-button>
          <u-button class="two" type="primary" @click="confirmStatus">
            确定
          </u-button>
        </view>
      </view>

      <view class="footer nyj-btns">
        <button class="cancel two" @click="resetFilter()">重置</button>
        <button type="primary" class="two" @click="confirmFilter()">
          确认
        </button>
      </view>
    </view>
  </u-popup>
</template>
<script>
  import { toast, timestampToChineseDate } from "@/utils/common";
  import { queryDictData, getPurDatas, getCoalDatas } from "@/api/statics.js";
  import {
    getLast30day,
    getDays,
    getdefaultMoth,
    formatDateFun,
    getDaysInMonth,
  } from "@/utils/formatTime";
  export default {
    props: {
      show: {
        type: Boolean,
        default: false,
      },
      dateType: {
        type: Number,
        default: 0,
      },
      customerType: {
        type: String,
        default: "100",
      },
    },
    watch: {
      customerType(newVal) {
        this.changeCustomer(newVal)
      },
      dateType(newVal) {
        // 这里能获取到完整的变化
        this.defaultDate();
      },
      keyword(newVal) {
        // 这里能获取到完整的变化
        this.search();
      },
      show(newVal) {
        // 这里能获取到完整的变化
        if (newVal) {
          this.showPopup = false
        }
      },
    },
    computed: {},
    created() {
      this.changeCustomer(100);
      this.defaultDate();
    },
    onShow() {

    },
    data() {
      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth() + 1;
      return {
        timeRangeMonth: "",
        minDate: "2020-01", // 最小可选年月
        maxDate: `${currentYear}-${currentMonth.toString().padStart(2, "0")}`, // 最大可选年月
        showDatePicker: false,
        showPicker: false,
        endTime: `${currentYear}-${currentMonth.toString().padStart(2, "0")}`,
        keyword: "",
        dataLists: [],
        showPopup: false,
        companyInfos: [],
        selectedText: "",
        statusList: [],
        timeRange: [],
        dateRangeValide: true,
        timeChangeShow: "",
        chooseStatusFlag: false,
        chooseComineFlag: false,
        filterInput: {
          customerIds: undefined,
          endTime: undefined,
          beginTime: undefined,
        },
      };
    },
    methods: {
      showDate() {
        this.showPicker = true;
      },
      // 清空输入框内容
      clearInput() {
        this.changeCustomer(this.customerType)
      },
      confirmEdate(e) {
        console.log("选择的月份范围:", e);
        this.timeRangeMonth = formatDateFun(e.value, "m");
        this.setTimeValue([this.timeRangeMonth]);
        this.showPicker = false;
      },
      confirmSdate(e) {
        console.log("选择的日期:", e);
        if (!!e && e.length > 1) {
          const d1 = new Date(e[0]);
          const d2 = new Date(e[1]);

          // 计算时间差（毫秒）
          const timeDiff = Math.abs(d2.getTime() - d1.getTime());

          // 转换为天数
          const diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
          if (diffDays > 60) {
            this.dateRangeValide = false;
            uni.showToast({
              title: "选择日期范围不能超过60天",
              icon: "none",
            });
            return;
          } else {
            this.dateRangeValide = true;
            this.timeChangeShow = e[0] + "至" + e[e.length - 1];
            this.setTimeValue([e[0], e[e.length - 1]]);
            this.showDatePicker = false;
          }
        }
      },
      setTimeValue(time) {
        let eDatef = "",
          sDatef = "";
        if (this.dateType == 0) {
          eDatef = time[1];
          sDatef = time[0];
        } else {
          eDatef =
            time[0] +
            "-" +
            getDaysInMonth(time[0].split("-")[0], time[0].split("-")[1]);
          sDatef = time[0] + "-01";
        }
        this.$set(this.filterInput, "endTime", eDatef);
        this.$set(this.filterInput, "beginTime", sDatef);
      },
      search() {
        this.dataLists = this.companyInfos.filter((e) =>
          e.text.includes(this.keyword)
        );
      },
      defaultDate() {
        let eDatef = "",
          sDatef = "";
        if (this.dateType == 0) {
          let sDate = getLast30day(30);
          let eDate = getDays();
          eDatef = eDate;
          sDatef = sDate;
          this.timeChangeShow = sDate + "至" + eDate;
          this.timeRange = [sDate, eDate];
        } else {
          let today = new Date();
          let tYear = today.getFullYear();
          let tMonth = today.getMonth() + 1;
          eDatef = `${tYear}-${tMonth}-` + getDaysInMonth(tYear, tMonth);
          sDatef = `${tYear}-${tMonth}-01`;
          this.endTime = `${tYear}-${tMonth}`;
          this.timeRangeMonth = `${tYear}-${tMonth}`;
        }
        this.$set(this.filterInput, "endTime", eDatef);
        this.$set(this.filterInput, "beginTime", sDatef);
      },
      timeChange(e) {
        const LIMIT = 100 * 24 * 3600 * 1000;
        // if (e[1] - e[0] > LIMIT) {
        //   toast('最大查询100天数据')
        //   return
        // }
        this.filterInput.beginTime = timestampToChineseDate(e[0]);
        this.filterInput.endTime = timestampToChineseDate(e[1]);
      },
      changeCustomer(e) {
        this.companyInfos = [];
        this.dataLists = [];
        this.selectedText = "";
        this.filterInput.customerIds = undefined;
        if (!!e) {
          if (e == 100) {
            this.getCompaniesCoal(e);
          } else {
            this.getCompanies(e);
          }
        }
      },
      // 获取企业信息-非煤
      async getCompanies(e) {
        let res = await getPurDatas(e);
        if (res.code == 200) {
          res.rows.forEach((e) => {
            this.companyInfos.push({
              value: e.id,
              text: e.customerName,
              checked: false,
            });
          });
          this.dataLists = this.companyInfos
        }
      },
      // 获取企业信息-煤矿
      async getCompaniesCoal(e) {
        let res = await getCoalDatas(e);
        if (res.code == 200) {
          res.rows.forEach((e) => {
            this.companyInfos.push({
              value: e.enterpriseId,
              text: e.enterpriseName,
              checked: false,
            });
          });
          this.dataLists = this.companyInfos
        }
      },
      popChange(data) {
        this.$emit("openChange", {
          key: "isOpenFilterBox",
          show: data.show,
        });
      },
      closePop() {
        this.$emit("closePop");
      },
      resetForm(val = '100') {
        this.$nextTick(() => {
          this.changeCustomer(val)
          this.defaultDate();
        });
      },
      resetFilter() {
        this.dateRangeValide = true;
        this.$set(this.filterInput, "customerIds", undefined);
        this.selectedText = "";
        this.defaultDate();
        this.dataLists = this.companyInfos.map((e) => {
          e.checked = false;
          return e;
        });
      },
      cancleStatus() {
        this.showPopup = false;
      },
      confirmStatus() {
        const filterList = this.dataLists
          .filter((e) => !!e.checked)
          .map((m) => m.value);
        this.filterInput.customerIds = filterList;
        let textList = this.dataLists
          .filter((e) => !!e.checked)
          .map((m) => m.text);
        this.selectedText = textList.toString();
        this.showPopup = false;
      },
      chooseStatus() {
        if (this.companyInfos.length === 0) {
          toast("企业名称列表暂时为空");
          return;
        }
        this.dataLists = this.companyInfos;
        this.keyword = "";
        this.showPopup = true;
      },
      statusClickItem(item) {
        this.dataLists = this.dataLists.map((e) => {
          if (item.value === e.value) {
            e.checked = !item.checked;
          }
          return e;
        });
        this.chooseStatusFlag = false;
      },
      confirmFilter() {
        if (this.dateRangeValide) {
          this.$emit("filterChange", this.filterInput);
          this.$emit("closePop");
        } else {
          uni.showToast({
            title: "选择日期范围不能超过60天",
            icon: "none",
          });
        }
      },
    },
  };
</script>
<style lang="scss" scoped>
  .name-close-icon {
    position: absolute;
    right: 48rpx;
    width: 48rpx;
    height: 48rpx;
    color: rgb(192, 196, 204);
    font-size: 24px;
    font-family: uniicons;
    text-decoration: none;
    text-align: center;
    z-index: 1;
  }

  .name-close-icon:before {
    content: "\e66d";
  }

  .input-pop {
    border-radius: 10px 10px 0 0 !important;
    background-color: #ffffff;
    height: 763rpx;

    .conent-wrap {
      display: flex;
      flex-direction: column;
      position: relative;
      height: 684rpx;
      margin-bottom: 200rpx;
    }

    .header {
      position: relative;
      padding: 21.33rpx 35.56rpx;
      text-align: center;
      border-bottom: 1.78rpx solid #eaeaea;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .close-icon {
        position: absolute;
        right: 35.56rpx;
      }

      uni-text {
        font-size: 32rpx !important;
        font-family: PingFang SC, PingFang SC-500;
        font-weight: 500;
        color: #000000;
        width: 100%;
      }

      text {
        font-size: 26.67rpx;
        font-weight: bold;
      }
    }

    .main {
      padding: 35.56rpx 35.56rpx 0 35.56rpx;
      flex: 1;
      height: 0;
      overflow-y: auto;
    }

    .footer {
      padding: 21.33rpx 35.56rpx 20rpx 35.56rpx;
      display: flex;
      justify-content: space-between;
      position: absolute;
      width: 100%;
    }
  }

  .nyj-scroll-pop {
    position: absolute;
    bottom: 0;
    height: 700rpx;
    z-index: 9;
    width: 100%;
    background-color: #fff;
  }

  .scroll-view {
    padding: 17.78rpx 35.56rpx 0 35.56rpx;
    width: 100%;
    height: 548rpx;

    .scroll-view-item+.scroll-view-item {
      margin-top: 10.67rpx;
    }

    .search-box {
      margin: 0 0 23.11rpx 5.33rpx;
    }

    .scroll-main {
      height: 440rpx;
      overflow-y: auto;
    }

    .scroll-view-item {
      display: flex;
      justify-content: space-between;
      padding: 14.22rpx 17.78rpx;
      border-radius: 7.11rpx;
      /* background-color: #f2f6fc; */

      .checked-icon {
        font-size: 24.89rpx;
        font-weight: bold;
      }
    }
  }

  .scroll-footer {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;

    button {
      margin: 0 !important;
    }
  }

  .items {
    .middle-icon {
      padding: 0 7.11rpx;
    }

    .label {
      width: 80px;
      margin-bottom: 7.11rpx;
      font-size: 29rpx;
      color: #333;
      font-weight: 400;
      font-family: PingFang SC, PingFang SC-400;

      >text {
        color: red;
      }
    }

    .items-input {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: start;
    }

    input {
      flex: 1;
      height: 71.11rpx;
      color: #999;
      line-height: 71.11rpx;
      border-radius: 7.11rpx;
      padding: 0px 17.78rpx;
      border: 1.78rpx solid #e5e5e5;
    }

    .select-wrap {
      flex: 1;
      height: 71.11rpx;
      padding: 0 17.78rpx;
      color: #808080;
      line-height: 71.11rpx;
      border-radius: 7.11rpx;
      border: 1.78rpx solid #e5e5e5;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .address-box {
      display: flex;
      flex: 1;

      button {
        width: 36%;
        margin-left: 17.78rpx;
      }
    }

    button {
      margin-top: 0 !important;
    }
  }
</style>